package cn.wolfcode.rbac.config;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration   //该类是配置类
@EnableCaching   //开启SpringCache缓存注解功能
@EnableConfigurationProperties(CacheProperties.class)  //加载yml的配置到CacheProperties类中
public class RedisCacheConfig {

    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
//        实现化默认配置对象
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
//        设置缓存key的序列化方式
        config = config.serializeKeysWith(
                RedisSerializationContext.SerializationPair.fromSerializer(
                        new StringRedisSerializer()));

//        设置缓存value的序列化方式(JSON格式)
        config = config.serializeValuesWith(
                RedisSerializationContext.SerializationPair.fromSerializer(
                        new GenericJackson2JsonRedisSerializer()));
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
//        设置缓存过期时间
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
//        是否开启key前缀 即 注解中的value属性
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }

//        是否开启缓存空值，防止缓存穿透
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        return config;
    }
}
